package com.youth.youthservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youth.youthservice.entity.*;
import com.youth.youthservice.entity.chapter.ChapterVo;
import com.youth.youthservice.entity.vo.CourseVo.*;
import com.youth.ClientEntity.OrderCourse;
import com.youth.commonutils.BeanCopyUtils;
import com.youth.commonutils.R;
import com.youth.servicebase.exceptionhandler.GlobalException;
import com.youth.youthservice.client.MemberClient;
import com.youth.youthservice.entity.announcement.CourseMember;
import com.youth.youthservice.entity.announcement.Course;
import com.youth.youthservice.entity.announcement.Student;
import com.youth.youthservice.mapper.CourseMemberMapper;
import com.youth.youthservice.mapper.EduCourseMapper;
import com.youth.youthservice.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.management.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author CM
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Resource
    private CourseMemberMapper courseMemberMapper;

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduSubjectService subjectService;

    @Autowired
    private EduTeacherService teacherService;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private EduCourseCollectService courseCollectService;

    @Autowired
    private EduCommentService commentService;


    @Override
    public ArrayList<Course> selectCourse() {
        List<EduCourse> eduCourses;
        ArrayList<Course> courses = new ArrayList<>();
        /*1.得到所有的课程ids*/
        eduCourses = baseMapper.selectList(new QueryWrapper<EduCourse>().select("id"));
        ArrayList<String> courseIds = new ArrayList<>();
        eduCourses.stream()
                .forEach(eduCourse -> courseIds.add(eduCourse.getId()));
        /*2.根据课程id查询学生ids*/
        courseIds.stream()
                .forEach(courseId -> {
                    /*选取了当前课程的学生*/
                    List<Student> curCourseStudents = courseMemberMapper.listStudentByCourseId(courseId);
                    Course course = new Course();
                    course.setChildren(curCourseStudents);
                    EduCourse entity = baseMapper.selectOne(new QueryWrapper<EduCourse>().eq("id", courseId).select("title"));
                    course.setValue(courseId);
                    course.setLabel(entity.getTitle());
                    courses.add(course);
                });
        return courses;
    }

    /*根据课程id去查询订单里面的课程信息，用于远程调用*/
    @Override
    public OrderCourse orderCourse(String courseId) {
        OrderCourse orderCourse = baseMapper.orderCourse(courseId);
        System.out.println("查询到的订单课程：" + orderCourse);
        return orderCourse;
    }

    /*分页查询课程列表*/
    @Override
    public R listCourseByPage(Long pageNum, Long pageSize, CourseQuery courseQuery) {
        LambdaQueryWrapper<EduCourse> queryWrapper = new LambdaQueryWrapper<>();
        /*判断参数是否为空*/
        if (courseQuery != null) {
            String subjectId = courseQuery.getSubjectId();
            String subjectParentId = courseQuery.getSubjectParentId();
            String title = courseQuery.getTitle();
            String teacherId = courseQuery.getTeacherId();
            /*判断筛选参数是否存在，填充查询条件*/
            queryWrapper.eq(StringUtils.hasText(subjectId), EduCourse::getSubjectId, subjectId);
            queryWrapper.eq(StringUtils.hasText(subjectParentId), EduCourse::getSubjectParentId, subjectParentId);
            queryWrapper.like(StringUtils.hasText(title), EduCourse::getTitle, title);
            queryWrapper.eq(StringUtils.hasText(teacherId), EduCourse::getTeacherId, teacherId);
        }
        /*使用page接口查询*/
        IPage<EduCourse> page = new Page<>(pageNum, pageSize);
        IPage<EduCourse> res = page(page, queryWrapper);
        return R.ok().data("rows", res.getRecords()).data("total", res.getTotal());
    }

    /*添加课程信息*/
    @Override
    public R saveCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = BeanCopyUtils.copyBean(courseInfoVo, EduCourse.class);
        boolean save = save(eduCourse);
        /*添加课程简介*/
        EduCourseDescription description = new EduCourseDescription();
        description.setDescription(courseInfoVo.getDescription());
        description.setId(eduCourse.getId());
        boolean save1 = descriptionService.save(description);
        /*检查是否添加成功*/
        if (!save || !save1) {
            throw new GlobalException(20001, "添加课程信息失败");
        }
        return R.ok().data("courseId", eduCourse.getId());
    }

    /*根据id查找课程信息，用于课程更新和发布课程时上一页回滚*/
    @Override
    public R getCourseInfoById(String id) {
        EduCourse eduCourse = getById(id);
        EduCourseDescription description = descriptionService.getById(id);
        CourseInfoVo res = BeanCopyUtils.copyBean(eduCourse, CourseInfoVo.class);
        res.setDescription(description.getDescription());
        return R.ok().data("courseInfoVo", res);
    }

    /*根据id更新课程信息*/
    @Transactional(rollbackFor = GlobalException.class)
    @Override
    public R updateCourseInfo(CourseInfoVo courseInfoVo) {
        /*更新course表*/
        EduCourse eduCourse = BeanCopyUtils.copyBean(courseInfoVo, EduCourse.class);
        boolean update1 = updateById(eduCourse);
        /*更新courseDescription表*/
        EduCourseDescription description = descriptionService.getById(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        boolean update2 = descriptionService.updateById(description);
        /*检查更新*/
        if (!update1 || !update2) {
            throw new GlobalException(20003, "课程更新失败");
        }
        return R.ok();
    }

    /*供课程发布页面展示待发布课程信息*/
    @Override
    public R getPublishCourseInfo(String id) {
        /*根据id获取当前课程的数据库信息*/
        EduCourse eduCourse = getById(id);
        CoursePublishVo vo = BeanCopyUtils.copyBean(eduCourse, CoursePublishVo.class);
        /*封装其余信息:使用这种方式每次都会查询出一整个实体，效率比较低*/
        vo.setPrice(eduCourse.getPrice().toString());
        vo.setDescription(descriptionService.getById(id).getDescription());
        // todo 如果一级科目和二级科目是一样的，这里可能会报错
        vo.setOneSubject(subjectService.getById(eduCourse.getSubjectParentId()).getTitle());
        vo.setTwoSubject(subjectService.getById(eduCourse.getSubjectId()).getTitle());
        vo.setTeacherName(teacherService.getById(eduCourse.getTeacherId()).getName());
        /*封装为PublishVo*/
        return R.ok().data("coursePublishVo", vo);
    }

    /*删除课程和课程简介，同时删除课程下的章节和小节*/
    @Override
    @Transactional(rollbackFor = GlobalException.class)
    public R delete(String courseId) {
        try {
            /*先删除课程本体*/
            removeById(courseId);
            /*删除其下的课程简介*/
            descriptionService.removeById(courseId);
            /*删除章节和小节*/
            QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id", courseId);
            List<EduChapter> chapterList = chapterService.list(queryWrapper);
            chapterList.stream().forEach(eduChapter -> {
                chapterService.deleteById(eduChapter.getId());
            });
            /*删除课程评论*/
            QueryWrapper<EduComment> commentQueryWrapper = new QueryWrapper<>();
            commentQueryWrapper.eq("course_id", courseId);
            commentService.remove(commentQueryWrapper);
            /*删除课程收藏*/
            QueryWrapper<EduCourseCollect> collectQueryWrapper = new QueryWrapper<>();
            collectQueryWrapper.eq("course_id", courseId);
            courseCollectService.remove(collectQueryWrapper);
        } catch (Exception e) {
            throw new GlobalException(20004, "课程删除失败");
        }
        return R.ok();
    }

    /*得到课程信息*/
    @Override
    public R getCourseInfoList() {
        ArrayList<CourseSimpleVo> courseSimpleVos = new ArrayList<>();
        /*查询数据库*/
        List<EduCourse> eduCourses = baseMapper.selectList(new QueryWrapper<EduCourse>());
        System.out.println("eduCourses:" + eduCourses);
        /*封装为vo对象*/
        eduCourses.stream()
                .forEach(eduCourse -> {
                    CourseSimpleVo courseSimpleVo = new CourseSimpleVo();
                    courseSimpleVo.setValue(eduCourse.getId());
                    courseSimpleVo.setLabel(eduCourse.getTitle());
                    courseSimpleVos.add(courseSimpleVo);
                });
        return R.ok().data("res", courseSimpleVos);
    }

    @Override
    public R listCourse(Long pageNum, Long pageSize, CourseQueryVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        /*检查查询参数是否为空*/
        queryWrapper.like(!StringUtils.isEmpty(courseQuery.getTitle()), "title", courseQuery.getTitle());
        queryWrapper.eq(!StringUtils.isEmpty(courseQuery.getSubjectParentId()), "subject_parent_id", courseQuery.getSubjectParentId());
        queryWrapper.eq(!StringUtils.isEmpty(courseQuery.getSubjectId()), "subject_id", courseQuery.getSubjectId());
        /*分别根据 购买数、更新时间、价格排序*/
        queryWrapper.orderByDesc(!StringUtils.isEmpty(courseQuery.getBuyCountSort()), "buy_count");
        queryWrapper.orderByDesc(!StringUtils.isEmpty(courseQuery.getGmtCreateSort()), "gmt_create");
        queryWrapper.orderByDesc(!StringUtils.isEmpty(courseQuery.getPriceSort()), "price");
        /*使用分页查询*/
        Page<EduCourse> page = new Page<>(pageNum, pageSize);
        /*结果风阻航道page中*/
        baseMapper.selectPage(page, queryWrapper);
        /*填充结果*/
        return R.ok().data("items", page.getRecords())
                .data("current", page.getCurrent())
                .data("pages", page.getPages())
                .data("size", page.getSize())
                .data("total", page.getTotal())
                .data("hasNext", page.hasNext())
                .data("hasPrevious", page.hasPrevious());
    }

    /*获取课程简介信息和对应课程讲师信息*/
    @Override
    public CourseWebVo getDetailById(String courseId) {
        /*更新课程浏览数*/
        updatePageViewCount(courseId);
        /*查询课程信息*/
        return baseMapper.getCourseDetailInfo(courseId);
    }

    /*点击课程详情页后更新课程浏览数*/
    private void updatePageViewCount(String courseId) {
        EduCourse eduCourse = getById(courseId);
        eduCourse.setViewCount(eduCourse.getViewCount() + 1);
        updateById(eduCourse);
    }

    /*获取当前课程的章节信息*/
    @Override
    public List<ChapterVo> getChapterList(String courseId) {
        return chapterService.getChapterByCourseId(courseId);
    }

    /*根据讲师id查询课程列表*/
    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper();
        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");
        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public List<String> getCourseIdByCourseName(String courseName) {
        List<String> ids = baseMapper.getCourseIdByTitle(courseName);
        return ids;
    }

}
